package com.xxx.servlet;

import com.alibaba.fastjson.JSON;
import com.xxx.pojo.Dish;
import com.xxx.pojo.PageTools;
import com.xxx.service.Services;
import com.xxx.service.impl.DishServiceImpl;
import com.xxx.util.GetIdTime;
import com.xxx.util.JsonSwitchUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.*;
import java.util.Arrays;
import java.util.List;

@WebServlet( urlPatterns = "/dish/*")
@MultipartConfig
public class DishServlet extends BaseServlet{
    private Services services = new DishServiceImpl();

    public void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        BufferedReader reader = req.getReader();
        String line = reader.readLine();

        PageTools pageTools = JSON.parseObject(line, PageTools.class);
//        System.out.println(pageTools);
        List<Dish> list = services.selectAll((pageTools.getPageNo() - 1) * pageTools.getPageSize(), pageTools.getPageSize());
        JsonSwitchUtil.toJsonString(req,resp,list);
    }

    public void selectByName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        BufferedReader reader = req.getReader();
        String line = reader.readLine();
        Dish dish = JSON.parseObject(line, Dish.class);
        Dish result= (Dish) services.selectByUsername(dish.getName());
        System.out.println(result);
        JsonSwitchUtil.toJsonString(req,resp,result);
    }

    public void updateById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        req.setCharacterEncoding("utf-8");
        BufferedReader reader = req.getReader();
        String line = reader.readLine();
        Dish[] dishes = JSON.parseObject(line, Dish[].class);
        System.out.println(dishes);
        int i=0;
        for (Dish dish : dishes) {
            dish.setUpdateTime(GetIdTime.getDataTime());
            i += services.updateById(dish);
        }
        JsonSwitchUtil.toJsonString(req,resp,i>=1);

    }

    /**
     * 上传模块，返回图片地址
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void upload(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        Part part= req.getPart("upload");
        long size = part.getSize();
        if (size == 0)
            return;
        String fileName = part.getSubmittedFileName();
        int i = fileName.lastIndexOf(".");
        String substring = fileName.substring(i);
        StringBuffer requestURL = req.getRequestURL();
        String uri = req.getRequestURI();
        int indexOf = requestURL.lastIndexOf(uri);
        String imgPath = requestURL.substring(0, indexOf) + req.getContextPath() + "/img/";
        System.out.println(uri + "  " + requestURL);
        long id = GetIdTime.getId();

        try (
                InputStream inputStream = part.getInputStream();
                OutputStream outputStream = new BufferedOutputStream(new FileOutputStream("E:\\JetBrains\\IdeaProjects\\java-web\\LS03_vuejs\\src\\main\\webapp\\img\\" + id +substring));
                OutputStream outputStreamTarGet = new BufferedOutputStream(new FileOutputStream("E:\\JetBrains\\IdeaProjects\\java-web\\LS03_vuejs\\target\\LS03_vuejs\\img\\" + id +substring))
                ){
            int len;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1){
                outputStreamTarGet.write(bytes,0,len);
                outputStream.write(bytes,0,len);

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        JsonSwitchUtil.toJsonString(req,resp, imgPath + id+substring);


    }

    public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        HttpSession session = req.getSession();
        Long userId = (Long) session.getAttribute("id");
        long id = GetIdTime.getId();
        String dataTime = GetIdTime.getDataTime();
        req.setCharacterEncoding("utf-8");
        BufferedReader reader = req.getReader();
        String line = reader.readLine();
        Dish dish = JSON.parseObject(line, Dish.class);
        dish.setPrice(dish.getPrice().setScale(2));
        dish.setId(id);
        dish.setOrder(null);
        dish.setCreateTime(dataTime);
        dish.setUpdateTime(dataTime);
        dish.setCreateUser(userId);
        dish.setUpdateUser(userId);
        System.out.println(dish);
        int i = services.add(dish);
        JsonSwitchUtil.toJsonString(req,resp,i==1);
    }


    public void selectCount(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        int i = services.selectCount();
        JsonSwitchUtil.toJsonString(req,resp,i);
    }

    public void deleteById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        req.setCharacterEncoding("utf-8");

        BufferedReader reader = req.getReader();
        String line = reader.readLine();
        Dish[] dishes = JSON.parseObject(line, Dish[].class);
        int i=0;
        for (Dish dish : dishes) {
            //删除图片
            File file1 = new File("E:\\JetBrains\\IdeaProjects\\java-web\\LS03_vuejs\\src\\main\\webapp\\img\\" + dish.getImg().substring(dish.getImg().lastIndexOf('/')));
            File file2 = new File("E:\\JetBrains\\IdeaProjects\\java-web\\LS03_vuejs\\target\\LS03_vuejs\\img\\" + dish.getImg().substring(dish.getImg().lastIndexOf('/')));
            boolean delete = file1.delete();
            file2.delete();
            i += services.delete(Long.valueOf(dish.getId()));
        }
        JsonSwitchUtil.toJsonString(req,resp,i >= 1);

    }

    public void updateDish(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        req.setCharacterEncoding("utf-8");
        BufferedReader reader = req.getReader();
        String line = reader.readLine();
//        System.out.println(line);
        Dish[] dishs = JSON.parseObject(line, Dish[].class);
//        System.out.println(dishs);
        int i=0;
        for (Dish dish : dishs) {
            dish.setUpdateTime(GetIdTime.getDataTime());
             i += services.updateById(dish);
        }

        JsonSwitchUtil.toJsonString(req,resp,i >= 1);
    }
}
